package jsyf.oa.service.email;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.DateUtils;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.email.*;
import jsyf.oa.dao.system.*;
import jsyf.oa.dao.wechat.service_company.TokenDao;
import jsyf.oa.entity.attach.AttachModuleEntity;
import jsyf.oa.entity.attach.AttachmentEntity;
import jsyf.oa.entity.email.*;
import jsyf.oa.entity.system.MessageEntity;
import jsyf.oa.entity.system.MessageReceiverEntity;
import jsyf.oa.entity.system.UserEntity;
import jsyf.oa.facade.email.EmailFacade;
import jsyf.oa.ientity.IBaseEntity;
import org.apache.catalina.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.*;

/**
 * Created by Administrator on 2017/11/1 0001.
 */
@Service
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class EmailService implements EmailFacade {
    @Autowired
    private EmailDao emailDao;
    @Autowired
    private InboxDao inboxDao;
    @Autowired
    private EmailReceiverDao emailReceiverDao;
    @Autowired
    private WreportReceiverCopiersDao wreportReceiverCopiersDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private GroupDao groupDao;
    @Autowired
    private DepartDao departDao;
    @Autowired
    private EmailReceiverAllDao emailReceiverAllDao;
    @Autowired
    private TokenDao tokenDao;
    @Autowired
    private CheckDao checkDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private MessageReceiverDao messageReceiverDao;
    @Autowired
    private RegionDao regionDao;

    @Override
    public String sendEmail(String params) {
        String type = "0";
        JSONObject jsonParam = FastJsonConvert.convertJSONToObject(params, JSONObject.class);
        if (jsonParam.containsKey("type")) {
            type = jsonParam.getString("type");
        }

        EmailEntity model = JSON.toJavaObject(JSON.parseObject(params), EmailEntity.class);
        //保存邮件主表
        EmailMainEntity emailMainEntity = model.getMains();
        String receiversIds = "";
        String receiversUserIds = "";
        if (StringUtils.isBlank(emailMainEntity.getContent())) {
            emailMainEntity.setContent(emailMainEntity.getContent().trim());
        }
        if ("0".equals(emailMainEntity.getId()) || com.alibaba.dubbo.common.utils.StringUtils.isBlank(emailMainEntity.getId())) {
            emailDao.addEmail(emailMainEntity);
        } else {
            JSONObject oldObj = emailDao.getJSONById(emailMainEntity.getId());
            EmailMainEntity oldEntity = JSON.toJavaObject(oldObj, EmailMainEntity.class);
            oldEntity.setSubject(emailMainEntity.getSubject());
            oldEntity.setContent(emailMainEntity.getContent());
            oldEntity.setEtype(emailMainEntity.getEtype());
            oldEntity.setDataId(emailMainEntity.getDataId());
            oldEntity.setParentId(emailMainEntity.getParentId());
            oldEntity.setUpdateUserId(emailMainEntity.getUpdateUserId());
            oldEntity.setDraft(emailMainEntity.getDraft());
            emailDao.update(oldEntity);
        }
        String emailId = emailMainEntity.getId();
        //删除之前收件人，抄送人
        emailReceiverDao.removeByCondition(" AND EMAIL_ID=?", new String[]{emailId});
        List<String> receiverIds = new ArrayList<>();
        //保存邮件关联表---
        if (model.getReceivers() != null && model.getReceivers().size() > 0) {
            for (EmailReceiverEntity emailReceiverEntity : model.getReceivers()) {
                if (!receiverIds.contains(emailReceiverEntity.getUserId())) {
                    receiversIds = receiversIds + emailReceiverEntity.getUserId() + "|";
                    emailReceiverEntity.setEmailId(emailId);
                    emailReceiverEntity.setUserType(0);
                    emailReceiverEntity.setSenderId(emailMainEntity.getCreateUserId());
                    emailReceiverEntity.setEType(emailMainEntity.getEtype());
                    emailReceiverEntity.setReportDate(emailMainEntity.getReportDate());
                    emailReceiverEntity.setDataId(emailMainEntity.getDataId());
                    emailReceiverEntity.setSubject(emailMainEntity.getSubject());
                    emailDao.addEmailReceiver(emailReceiverEntity);
                }
            }
        }
        if (emailMainEntity.getEtype() == 1) {
            wreportReceiverCopiersDao.removeByCondition(" and sender_user_id=?", new String[]{emailMainEntity.getCreateUserId()});
            //保存手动添加的收件人
            if (model.getHandAddReceivers() != null && model.getHandAddReceivers().size() > 0) {
                for (WreportReceiverCopiersEntity wreportReceiverCopiersEntity : model.getHandAddReceivers()) {
                    if (!receiverIds.contains(wreportReceiverCopiersEntity.getUserId())) {
                        JSONObject userJson = userDao.getJSONById(wreportReceiverCopiersEntity.getUserId());
                        wreportReceiverCopiersEntity.setType(0);
                        wreportReceiverCopiersEntity.setSenderUserId(emailMainEntity.getCreateUserId());
                        wreportReceiverCopiersEntity.setUserName(userJson.getString("name"));
                        wreportReceiverCopiersEntity.setReportDate(emailMainEntity.getReportDate());
                        wreportReceiverCopiersEntity.setwId(emailMainEntity.getDataId());
                        wreportReceiverCopiersDao.add(wreportReceiverCopiersEntity);
                    }
                }

            }

            //保存手动添加的抄送人
            if (model.getHandAddCopiers() != null && model.getHandAddCopiers().size() > 0) {
                wreportReceiverCopiersDao.removeByCondition(" and sender_user_id=? and type=1", new String[]{emailMainEntity.getCreateUserId()});
                for (WreportReceiverCopiersEntity wreportReceiverCopiersEntity : model.getHandAddCopiers()) {
                    if (!receiverIds.contains(wreportReceiverCopiersEntity.getUserId())) {
                        JSONObject userJson = userDao.getJSONById(wreportReceiverCopiersEntity.getUserId());
                        wreportReceiverCopiersEntity.setType(1);
                        wreportReceiverCopiersEntity.setUserName(userJson.getString("name"));
                        wreportReceiverCopiersEntity.setSenderUserId(emailMainEntity.getCreateUserId());
                        wreportReceiverCopiersEntity.setReportDate(emailMainEntity.getReportDate());
                        wreportReceiverCopiersEntity.setwId(emailMainEntity.getDataId());
                        wreportReceiverCopiersDao.add(wreportReceiverCopiersEntity);
                    }
                }
            }
        }

        //保存邮件关联表---抄送人
        if (model.getCopiers() != null && model.getCopiers().size() > 0) {
            for (EmailReceiverEntity emailReceiverEntity : model.getCopiers()) {
                if (!receiverIds.contains(emailReceiverEntity.getUserId())) {
                    if (type.equals("1")) {
                        receiversIds = receiversIds + emailReceiverEntity.getUserId() + "|";
                    }
                    emailReceiverEntity.setEmailId(emailId);
                    emailReceiverEntity.setUserType(1);
                    emailReceiverEntity.setSenderId(emailMainEntity.getCreateUserId());
                    emailReceiverEntity.setEType(emailMainEntity.getEtype());
                    emailReceiverEntity.setReportDate(emailMainEntity.getReportDate());
                    emailReceiverEntity.setDataId(emailMainEntity.getDataId());
                    emailReceiverEntity.setSubject(emailMainEntity.getSubject());
                    emailDao.addEmailReceiver(emailReceiverEntity);
                }
            }
        }
        //保存附件表
        if (model.getAttaches() != null && model.getAttaches().size() > 0) {
            for (AttachmentEntity attachModuleEntity : model.getAttaches()) {
                emailDao.attachesflag(attachModuleEntity.getId());
                AttachModuleEntity moduleEntity = new AttachModuleEntity();
                moduleEntity.setAttachId(attachModuleEntity.getId());
                moduleEntity.setAttachModule(1);
                moduleEntity.setModuleId(emailId);
                emailDao.addAttahModule(moduleEntity);
            }
        }

        //判读是否是回复邮件
        if (com.alibaba.dubbo.common.utils.StringUtils.isNotEmpty(emailMainEntity.getParentId()) && !emailMainEntity.getParentId().equals("0")) {
            List<IBaseEntity> list = emailReceiverDao.getIBaseEntityByCondition(" AND USER_ID = ? AND EMAIL_ID = ? ", new String[]{emailMainEntity.getCreateUserId(), emailMainEntity.getParentId()});
            if (list != null && list.size() > 0) {
                EmailReceiverEntity emailReceiverEntity = (EmailReceiverEntity) list.get(0);
                emailReceiverEntity.setReplyTime(emailReceiverDao.getCurrentTime());
                emailReceiverDao.update(emailReceiverEntity);
            }
        }
        if (receiversIds.length() > 0) {
            receiversUserIds = receiversIds.substring(0, receiversIds.length() - 1);
        }
        //给收件人发送消息
        if (emailMainEntity.getEtype() == 0 && emailMainEntity.getDraft() == 0) {
            //获取发送人姓名
            JSONObject sender = userDao.getJSONById(emailMainEntity.getCreateUserId());
            String content = sender.getString("name") + "给您发送了一份邮件" +
                    "\n主题为：" + emailMainEntity.getSubject() + "" +
                    "\n请注意查收";
            //企业号:发消息通知申请人  (不发送给抄送人)
            JSONObject msgObject = new JSONObject();
            msgObject.put("userIds", receiversUserIds);
            msgObject.put("content", content);
            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
        }

        return emailMainEntity.getId();
    }

    @Override
    public List<JSONObject> getOrgInbox(String currentUserId) {
        List<JSONObject> listResult = new ArrayList<>();
        List<JSONObject> listCompanies;
        List<JSONObject> listDeparts;
        List<JSONObject> listUsers;
        List<JSONObject> listGroup = groupDao.getJSONListByCondition(" AND CREATE_USER_ID= ? ORDER BY SORT_NO ", new Object[]{currentUserId});

        if (userDao.isSuperUser(currentUserId)) {
            //查询所有公司
            listCompanies = getCompanyByAll();
            //查询所有部门
            listDeparts = getDepartLevel1();
            //查询所有人
            listUsers = getUserByAll();
        } else {
            List<String> listSuperUser = new ArrayList<String>();
            listSuperUser.add("201711271733404C9DA1461F2421F828");//曹国玉
            listSuperUser.add("2017121616084F0B9E200AC4144BD435");//李丽平
            listSuperUser.add("2017121616304595BB1D12C91392E04E");//王转转
            listSuperUser.add("20171217130247059F2B10DB2BE1B5C7");//侯娇艳
            listSuperUser.add("201712161851433BAD8487BE30159C9E");//贾贤达
            listSuperUser.add("2017121712504EF7A2E3DF56DFD984B8");//严艳娥
            listSuperUser.add("20171217125148A3A54B5B67B191A36F");//徐敏
            listSuperUser.add("201712171253420DBBFAE64C57F955B9");//邓继英
            listSuperUser.add("201712171257484DA20FEC7F96A76B3D");//靳悦双
            listSuperUser.add("20171219122040B28198B030F64B7D37");//林恩智
            listSuperUser.add("20171219123942AAAA074F6A41D82ABF");//刘新华
            listSuperUser.add("2017121921544B71AAD69E89E3D5E5A7");//张芳
            listSuperUser.add("20181029131941189298E733B95017AF");//贺建荣
            listSuperUser.add("2017121618514C22B68296F31AF8DDE2");//谈小中
            //listSuperUser.add("20180131151244DAB90938CE703BB1C8");//针宏佳
            //listSuperUser.add("2018030511004F2994125005B39F203C");//段艳珍
            List<JSONObject> users = userDao.getViewJSONListByCondition(" and id = ?", new Object[]{currentUserId});
            List<String> listCompanyIds = new ArrayList<>();
            for (int i = 0; i < users.size(); i++) {
                String companyId = users.get(i).getString("companyId");
                listCompanyIds.add(companyId);
                if (listSuperUser.contains(currentUserId)) {
                    companyDao.getChildrenIds(companyId, listCompanyIds);
                }
            }
            String companyIds = "";
            for (int i = 0; i < listCompanyIds.size(); i++) {
                companyIds += "'" + listCompanyIds.get(i) + "',";
            }
            companyIds = companyIds.substring(0, companyIds.length() - 1);
            listCompanies = companyDao.getJSONListByCondition(" AND DEL_FLAG = 0 AND ID IN(" + companyIds + ") ORDER BY SORT_NO ", new Object[]{});
            listDeparts = getDepartLevel1(companyIds);
            String departIds = "";
            for (int i = 0; i < listDeparts.size(); i++) {
                departIds += "'" + listDeparts.get(i).getString("id") + "',";
            }
            departIds = departIds.substring(0, departIds.length() - 1);
            listUsers = userDao.getViewJSONListByCondition(" AND main=1 AND jobState!=1 AND departId IN(" + departIds + ") ORDER BY companySortNo,departSortNo,roleSortNo,userSortNo ", new Object[]{});
        }

        //根节点root
        JSONObject objRoot = new JSONObject();
        objRoot.put("id", "0");
        objRoot.put("name", "收件箱");
        objRoot.put("type", "root");
        objRoot.put("open", true);
        objRoot.put("isParent", true);
        listResult.add(objRoot);

        //添加自定义分组节点
        listResult = getGroupByUser(listGroup, listResult);
        //查询人员
        for (int j = 0; j < listUsers.size(); j++) {
            JSONObject objUser = listUsers.get(j);
            if ("大区经理".equals(objUser.getString("roleName"))) {
                objUser.put("name", objUser.getString("name") + "(" + "大区" + ")");
            }
            objUser.put("pId", objUser.getString("departId"));
            objUser.put("type", "user");
            listResult.add(objUser);
        }
        //添加部门节点
        for (int i = 0; i < listDeparts.size(); i++) {
            JSONObject objDepart = listDeparts.get(i);
            String departId = objDepart.getString("id");
            String parentId = objDepart.getString("parentId");
            String companyId = objDepart.getString("companyId");
            if (com.alibaba.dubbo.common.utils.StringUtils.isEmpty(parentId) || ("0").equals(parentId)) {
                objDepart.put("pId", companyId);
            } else {
                objDepart.put("pId", parentId);
            }
            objDepart.put("type", "depart");
            objDepart.put("dataId", departId);
            objDepart.put("isParent", true);
            listResult.add(objDepart);
        }
        //添加公司节点
        for (int i = 0; i < listCompanies.size(); i++) {
            JSONObject objCompany = listCompanies.get(i);//id,name,sortNo,
            String parentId = objCompany.getString("parentId");
            if ("0".equals(listCompanies.get(0).getString("parentId"))) {
                if (com.alibaba.dubbo.common.utils.StringUtils.isEmpty(parentId) || ("0").equals(parentId)) {
                    objCompany.put("pId", "0");
                    objCompany.put("open", true);
                } else {
                    objCompany.put("pId", parentId);
                    objCompany.put("open", false);
                }
            } else {
                objCompany.put("pId", "0");
                objCompany.put("open", true);
            }
            objCompany.put("type", "company");
            objCompany.put("isParent", true);
            listResult.add(objCompany);
        }

        return listResult;
    }


    @Override
    public JSONObject findInboxList(JSONObject jsonObject, Integer requestPage, Integer pageSize) {
        JSONObject result = new JSONObject();
        JSONObject objSendData = new JSONObject();
        //查询收件箱列表
        String userId = jsonObject.getString("userId");
        String senderId = jsonObject.getString("senderId");
        String senderIds = jsonObject.getString("senderIds");
        String searchKey = jsonObject.getString("searchKey");
        String departId = jsonObject.getString("departId");
        String companyId = jsonObject.getString("companyId");
        String type = jsonObject.getString("type");
        String etype = jsonObject.getString("etype");
        StringBuilder sbCondition = new StringBuilder();
        List<Object> sqlArgs = new ArrayList<Object>();
        sbCondition.append(" AND userId = '" + userId + "' ");

        switch (type) {
            case "company":
                List<JSONObject> listCompanys = companyDao.getJSONListByCondition(
                        " AND PARENT_ID=? AND DEL_FLAG = 0", new Object[]{companyId});
                if (listCompanys != null && listCompanys.size() > 0) {
                    String companyIds = "";
                    for (int i = 0; i < listCompanys.size(); i++) {
                        companyIds += "'" + listCompanys.get(i).getString("id") + "',";
                    }
                    companyIds = companyIds.substring(0, companyIds.length() - 1);
                    sbCondition.append(" AND companyId IN (" + companyIds + ")");
                } else {
                    sbCondition.append(" AND companyId = ? ");
                    sqlArgs.add(companyId);
                }
                break;
            case "depart":
                List<JSONObject> listDeparts = departDao.getJSONListByCondition(
                        " AND PARENT_ID=? AND DEL_FLAG = 0", new Object[]{departId});
                if (listDeparts != null && listDeparts.size() > 0) {
                    String departIds = "";
                    for (int i = 0; i < listDeparts.size(); i++) {
                        departIds += "'" + listDeparts.get(i).getString("id") + "',";
                    }
                    departIds = departIds.substring(0, departIds.length() - 1);
                    sbCondition.append(" AND departId IN (" + departIds + ")");
                } else {
                    sbCondition.append(" AND departId = ? ");
                    sqlArgs.add(departId);
                }

                break;
            case "region":
            case "group":
                String[] arrSenderIds = senderIds.split(",");
                String resultIds = "";
                for (int i = 0; i < arrSenderIds.length; i++) {
                    resultIds += "'" + arrSenderIds[i] + "',";
                }
                resultIds = resultIds.substring(0, resultIds.length() - 1);
                sbCondition.append("  AND createUserId IN (" + resultIds + ") ");
                break;
            case "user":
                sbCondition.append(" AND createUserId = '" + senderId + "' ");
                List<JSONObject> records = inboxDao.getViewAllByPage(sbCondition.toString(), requestPage, pageSize);
                int recordCount = inboxDao.getViewAllByCount(sbCondition.toString());
                int recordSize = Integer.valueOf(pageSize).intValue();
                //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
                int pageCount = recordCount % recordSize == 0 ? recordCount / recordSize : (recordCount / recordSize) + 1;
                //子对象
                objSendData.put("recordCount", recordCount);
                objSendData.put("pageCount", pageCount);
                objSendData.put("requestPage", 1);
                result.put("pager", objSendData);
                // 子数组对象
                result.put("records", records);
                return result;
            default:
                break;
        }
        if (!StringUtils.isBlank(searchKey)) {
            searchKey = searchKey.trim();
            sbCondition.append(" AND (sender LIKE " + "'%" + searchKey + "%' or subject LIKE " + "'%" + searchKey + "%') ");
            List<JSONObject> records = inboxDao.getViewAllByPage(sbCondition.toString(), requestPage, pageSize);
            int recordCount = inboxDao.getViewAllByCount(sbCondition.toString());
            int recordSize = Integer.valueOf(pageSize).intValue();
            //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
            int pageCount = recordCount % recordSize == 0 ? recordCount / recordSize : (recordCount / recordSize) + 1;
            //子对象
            objSendData.put("recordCount", recordCount);
            objSendData.put("pageCount", pageCount);
            objSendData.put("requestPage", 1);
            result.put("pager", objSendData);
            // 子数组对象
            result.put("records", records);
            return result;
        }
        if (!StringUtils.isBlank(etype)) {
            sbCondition.append(" AND etype !=? ");
            sqlArgs.add(etype);
        }
        sbCondition.append(" AND draft=0");
        sbCondition.append(" GROUP BY emailId ");
        sbCondition.append(" ORDER BY createTime DESC ");
        List<JSONObject> records = inboxDao.getViewJSONListByPage(sbCondition.toString(),
                sqlArgs.toArray(), requestPage, pageSize);
        int recordCount = inboxDao.getViewPageCount(sbCondition.toString(), sqlArgs.toArray());
        int recordSize = Integer.valueOf(pageSize).intValue();
        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % recordSize == 0 ? recordCount / recordSize : (recordCount / recordSize) + 1;
        //子对象
        objSendData.put("recordCount", recordCount);
        objSendData.put("pageCount", pageCount);
        objSendData.put("requestPage", 1);
        result.put("pager", objSendData);
        // 子数组对象
        result.put("records", records);
        return result;
    }

    @Override
    public JSONObject findInboxDetail(String emailId, String userId) {
        EmailEntity emailEntity = new EmailEntity();
        if (!StringUtils.isBlank(emailId)) {
            Integer row = inboxDao.emailReader(emailId, userId);
            if (row == 0) {
                inboxDao.emailReaderAll(emailId, userId);
            }
            emailEntity.setMains(inboxDao.getByEmailDetail(emailId));
            emailEntity.setReceivers(inboxDao.findByEmailReceiver(emailId, "0"));
            emailEntity.setCopiers(inboxDao.findByEmailReceiver(emailId, "1"));
            emailEntity.setAttaches(inboxDao.findByAttaches(emailId));
        }
        return (JSONObject) JSON.toJSON(emailEntity);
    }

    @Override
    public Boolean findEmailAll(String jsonData) {
        JSONObject jsonObject = JSON.toJavaObject(JSON.parseObject(jsonData), JSONObject.class);
        String dateTime = jsonObject.getString("dateTime");
        List<JSONObject> userList = emailDao.getEmailByUser();
        for (int i = 0; i < userList.size(); i++) {
            String userId = userList.get(i).getString("userId");
            Integer count = emailDao.getEmailCount(userId, dateTime);
            if (count == 0) {
                List<JSONObject> emailReceiver = emailDao.getEmailReceiverAll(userId);
                JSONObject email = emailDao.getEmailId(userId, dateTime);
                if (email != null) {
                    String emailId = email.getString("emailId");
                    if (emailReceiver != null && emailReceiver.size() > 0) {
                        for (int j = 0; j < emailReceiver.size(); j++) {
                            JSONObject receiver = emailReceiver.get(j);
                            EmailReceiverAllEntity emailReceiverAllEntity = new EmailReceiverAllEntity();
                            emailReceiverAllEntity.setEmailId(emailId);
                            emailReceiverAllEntity.setUserId(receiver.getString("userId"));
                            emailReceiverAllEntity.setUserName(receiver.getString("userName"));
                            emailReceiverAllEntity.setUserType(receiver.getInteger("userType"));
                            emailReceiverAllEntity.setReader(receiver.getInteger("reader"));
                            emailReceiverAllEntity.setSenderId(receiver.getString("senderId"));
                            emailReceiverAllEntity.setEType(receiver.getInteger("eType"));
                            emailReceiverAllEntity.setReportDate(receiver.getString("reportDate"));
                            emailReceiverAllEntity.setDataId(receiver.getString("dataId"));
                            emailReceiverAllEntity.setSubject(receiver.getString("subject"));
                            emailReceiverAllDao.add(emailReceiverAllEntity);
                        }
                    }
                }
            }
        }
        return true;
    }


    @Override
    public Integer unreadEmail(String userId) {
        String condition = " AND USER_ID=? AND READER=0";
        return emailReceiverDao.getPageCount(condition, new Object[]{userId});
    }


    private List<JSONObject> getCompanyByAll() {
        //查询公司
        return companyDao.getJSONListByCondition(" AND DEL_FLAG = 0 ORDER BY SORT_NO ", new Object[]{});
    }

    public List<JSONObject> getDepartLevel1() {
        //查询部门
        return departDao.getJSONListByCondition(" AND DEL_FLAG = 0  ORDER BY SORT_NO ", new Object[]{});
    }

    public List<JSONObject> getDepartLevel1(String companyIds) {
        //查询部门
        return departDao.getJSONListByCondition(" AND DEL_FLAG = 0  AND COMPANY_ID IN(" + companyIds + ") ORDER BY SORT_NO ", new Object[]{});
    }

    public List<JSONObject> getUserByAll() {
        //查询人员
        return userDao.getViewJSONListByCondition(" and main=1 and jobState!=1 ORDER BY companySortNo,departSortNo,roleSortNo,userSortNo ", new Object[]{});
    }

    public List<JSONObject> getGroupByUser(List<JSONObject> listGroup, List<JSONObject> listResult) {
        String groupId = "";
        for (int i = 0; i < listGroup.size(); i++) {
            JSONObject objGroup = listGroup.get(i);
            groupId = objGroup.getString("id");
            String groupName = objGroup.getString("groupName");
            String parentId = objGroup.getString("parentId");
            objGroup.put("id", groupId);
            if (com.alibaba.dubbo.common.utils.StringUtils.isEmpty(parentId) || ("0").equals(parentId)) {
                objGroup.put("pId", "0");
            } else {
                objGroup.put("pId", parentId);
            }
            objGroup.put("open", false);
            objGroup.put("name", groupName);
            objGroup.put("type", "group");
            objGroup.put("dataId", groupId);
            objGroup.put("isParent", true);
            listResult.add(objGroup);

            if (!StringUtils.isEmpty(groupId)) {
                List<JSONObject> users = userDao.getJSONListByCondition(" AND ID IN (SELECT USER_ID FROM T_SYS_USER_2_GROUP WHERE GROUP_ID =?) AND JOB_STATE!=1 ORDER BY SORT_NO", new Object[]{groupId});
                if (users != null && users.size() > 0) {
                    for (int j = 0; j < users.size(); j++) {
                        JSONObject objUser = new JSONObject();
                        objUser.put("id", users.get(j).getString("id"));
                        objUser.put("pId", groupId);
                        objUser.put("name", users.get(j).getString("name"));
                        objUser.put("type", "user");
                        objUser.put("dataId", users.get(j).getString("id"));
                        listResult.add(objUser);
                    }
                }
            }
        }

        return listResult;
    }

    @Override
    public Boolean setReadCloseTime(String userId, String emailId) {
        List<IBaseEntity> list = emailReceiverDao.getIBaseEntityByCondition(" AND USER_ID = ? AND EMAIL_ID = ? ", new String[]{userId, emailId});
        if (list != null && list.size() > 0) {
            EmailReceiverEntity emailReceiverEntity = (EmailReceiverEntity) list.get(0);
            emailReceiverEntity.setReadCloseTime(emailReceiverDao.getCurrentTime());
            emailReceiverDao.update(emailReceiverEntity);
        }
        return true;
    }

    @Override
    public Integer everyDayEmailMove() {
        return emailDao.everyDayEmailMove();
    }

    @Override
    public JSONObject getNotReadReport() {
        //获取今天的时间
        Calendar c = Calendar.getInstance();
        String dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        //获取昨天的时间
        String yesterday = DateUtils.getyesterdayByDateTime(dateTime);
        //添加规则（直接下级的阅读情况）
        Map<String, String> user = new LinkedHashMap<>();
        user.put("区域组长", "'区域经理'");
        user.put("大区经理", "'区域经理','区域组长'");
        user.put("区域总监", "'大区经理'");
        user.put("区域支持", "'区域总监'");
        //如果有异常，则添加id进这个List(发送过异常消息的userId集合)
        List<String> receiverUserIdList = new ArrayList<>();
        //按顺序循环Map，走流程。
        Iterator<Map.Entry<String, String>> iterator = user.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            //兼职的阅读人
            List<JSONObject> userList = userDao.getViewJSONListByCondition(" AND roleName = ? and jobState!=1 ", new Object[]{entry.getKey()});
            if (null != userList && userList.size() > 0) {
                for (int i = 0; i < userList.size(); i++) {
                    String userId = userList.get(i).getString("id");
                    //用来发消息时传递信息
                    JSONObject userJSONObject = new JSONObject();
                    userJSONObject.put("userId", userId);
                    userJSONObject.put("dateTime", DateUtils.nowDayByString(userDao.getCurrentTime()));
                    //查找所有的能看到的人，包括工作报告
                    String userIds = checkDao.getChilderByUserId(userId, true);
                    //主职位的发件人
                    List<JSONObject> userIdsList = userDao.getViewJSONListByCondition(" AND roleName in (" + entry.getValue() + ") and main=1 and id in (" + userIds + ")", new Object[]{});
                    String userIdList = "";
                    if (null != userIdsList && userIdsList.size() > 0) {
                        for (int j = 0; j < userIdsList.size(); j++) {
                            userIdList += "'" + userIdsList.get(j).getString("id") + "',";
                        }
                    } else {
                        userIdList = "'',";
                    }
                    userIdList = userIdList.substring(0, userIdList.length() - 1);
                    //查询出来的异常数量
                    Integer count = null;
                    if ("大区经理".equals(entry.getKey())) {
                        //查询大区经理岗位下的区域
                        List<JSONObject> regionList = regionDao.getPartJobRegionForDaQu(userId);
                        if (null != regionList && regionList.size() > 0) {
                            for (int j = 0; j < regionList.size(); j++) {
                                String newUserIdList = "";
                                //查询配置了这个区域的 -- 区域经理，区域组长 --
                                List<JSONObject> regionUserList = regionDao.getUserByRegionId("'区域经理','区域组长'", regionList.get(j).getString("id"), userIdList);
                                if (null != regionUserList && regionUserList.size() > 0) {
                                    for (int k = 0; k < regionUserList.size(); k++) {
                                        newUserIdList += "'" + regionUserList.get(k).getString("userId") + "',";
                                    }
                                } else {
                                    newUserIdList = "'',";
                                }
                                userIdList = newUserIdList.substring(0, newUserIdList.length() - 1);
                                //查询异常数量
                                count = emailDao.getNotReadReportByRoleName(userId, userIdList, yesterday, entry.getValue());
                                //有异常直接返回
                                if (null != count && count != 0) {
                                    break;
                                }
                            }
                        }
                    } else {
                        //查询异常数量
                        count = emailDao.getNotReadReportByRoleName(userId, userIdList, yesterday, entry.getValue());
                    }
                    //异常数量不为0时发消息
                    if (null != count && count != 0) {
                        //如果以前没有发过消息再发送，否则不发。
                        Boolean flag = false;
                        if (receiverUserIdList.indexOf(userId) < 0) {
                            receiverUserIdList.add(userId);
                            flag = true;
                        }
                        if (flag) {
                            String url = "";
                            String roleName = userDao.getViewJSONListByCondition(" and id=? and main=1 and jobState!=1", new Object[]{userId}).get(0).getString("roleName");
                            //主职位是大区经理和区域组长的发这个URL
                            if ("大区经理".equals(roleName) || "区域组长".equals(roleName) || "区域经理".equals(roleName)) {
                                url = "/reportForm/errorMessage/daQuReadApp.html?userId=" + userId + "&dateTime=" + dateTime;
                            } else {
                                url = "/reportForm/errorMessage/managerReadApp.html?userId=" + userId + "&dateTime=" + dateTime;
                            }
                            //发送消息
                            this.sendMessage(userJSONObject, url);
                        }
                    } else {
                        Boolean flag = false;
                        //如果是区域总监和区域支持，判断自己看到人里面下级是否在已有的发送List中，如果在，则发消息给自己。
                        if ("区域总监".equals(entry.getKey()) || "区域支持".equals(entry.getKey())) {
                            if (this.getErrorUserId(userIdsList, receiverUserIdList)) {
                                if (receiverUserIdList.indexOf(userId) < 0) {
                                    receiverUserIdList.add(userId);
                                    flag = true;
                                }
                                //发送消息
                                if (flag) {
                                    String url = "/reportForm/errorMessage/managerReadApp.html?userId=" + userId + "&dateTime=" + dateTime;
                                    this.sendMessage(userJSONObject, url);
                                }
                            }
                        }
                    }
                }
            }
        }
        JSONObject result = new JSONObject();
        result.put("records", "OK");
        return result;
    }

    //间接岗位判断下级是否有异常（发送过消息），有重复-true 无重复-false
    //比较两个List是否有重复的值
    private Boolean getErrorUserId(List<JSONObject> roleUserList, List<String> checkUserIdsList) {
        if (null == roleUserList || null == checkUserIdsList) {
            return false;
        }
        String[] roleUserIds = null;
        String userIds = "";
        //List取id,拼成字符串
        for (int i = 0; i < roleUserList.size(); i++) {
            userIds += roleUserList.get(i).getString("id") + ",";
        }
        if (!StringUtils.isBlank(userIds) && userIds.endsWith(",")) {
            userIds.substring(0, userIds.length() - 1);
        }
        //分割字符串为数组
        if (!StringUtils.isBlank(userIds) && userIds.length() > 3) {
            roleUserIds = userIds.split(",");
        }
        //List转换数组
        String[] checkUserIds = checkUserIdsList.toArray(new String[]{});
        //两个数组非空判断
        if (null != checkUserIds && null != roleUserIds) {
            //数组非空，排序。
            Arrays.sort(checkUserIds);
            Arrays.sort(roleUserIds);
        } else {
            return false;
        }
        //给初始的下标值
        int i = 0;
        int j = 0;
        //两个数组里面的值比较是否相同
        while (i < checkUserIds.length && j < roleUserIds.length) {
            if (checkUserIds[i].equals(roleUserIds[j])) {
                return true;
            } else {
                if (checkUserIds[i].compareTo(roleUserIds[j]) < 0) {
                    i++;
                } else if (checkUserIds[i].compareTo(roleUserIds[j]) > 0) {
                    j++;
                }
            }
        }
        return false;
    }

    public void sendMessage(JSONObject user, String url) {
        MessageEntity messageEntity = new MessageEntity();
        messageEntity.setCreateUserId(user.getString("userId"));
        messageEntity.setCreateTime(userDao.getCurrentTime());
        messageEntity.setContent("工作报告未读/未发送提醒");
        messageEntity.setMessageType(3);
        messageEntity.setDelFlag(0);
        messageEntity.setOpenUrl(url);
        messageEntity.setOpenTitle(String.format(REPORT_MESSAGE_ERROR));
        messageDao.add(messageEntity);
        //保存第一审核人信息到消息收件人表t_sys_message_receiver
        MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
        messageReceiverEntity.setMessageId(messageEntity.getId());
        messageReceiverEntity.setUserId(user.getString("userId"));
        messageReceiverEntity.setUserType(0);
        messageReceiverEntity.setReadFlag(0);
        messageReceiverDao.add(messageReceiverEntity);
        //发送企业微信
        JSONObject msgObject = new JSONObject();
        msgObject.put("userIds", messageEntity.getCreateUserId());
        msgObject.put("content", String.format(REPORT_MESSAGE_ERROR_WE,
                "http://oa.yingfeng365.com/page" + messageEntity.getOpenUrl()));
        tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
    }
}
